// featurePackage/pages/createMyWorks/createMyWorks.js
import {
  chooseMultipleOSSImgUploadQiniuAction
} from "../../../service/upload_service"
import { getFrontUploadSign } from "../../../service/config"
import { uploadOSSActicon } from '../../../service/upload_service'
import {
  createWorksReq,
  updateWorksReq,
  queryActivityList,//查询可参加的活动列表
  worksDetailReq,// 查询作品详情
} from "../../../service/jb_activity_service"
import debounce from "../../../tools/debounce"
import {
  VIDEO_COVER,
} from "../../../service/base_service"
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    videoCoverUrl: VIDEO_COVER,
    formData: {
      id: null,//作品id
      modelType: 0, //0:模版1,1：模版2 2：模版3
      title: '', //标题
      createName: "", //创建人
      images: [], //多图
      introduce: "", //简介
      coverPic: "", //封面
      voteId: "", //活动id
      voteName: "", //活动名称
      videoUrl: "", //短视频链接
      productIds: [],// 商品id
      // productName: "",// 商品名称
      voteNum: 0,// 投票数量
      rank: 0,//排名
      viewNum: 0,//浏览量
    },
    productId: "",
    productName: "",
    mulImgs: [
      // 'https://images.jiabao19.com/images/product/2024-04-01/1711950606076/面膜.jpg',
      // 'https://images.jiabao19.com/images/product/2024-04-01/1711950606074/黄金养肤套.jpg',
      // 'https://images.jiabao19.com/images/product/2024-04-01/1711950606079/眼霜.jpg',
      // 'https://images.jiabao19.com/images/product/2024-04-01/1711950606076/面膜.jpg',
      // 'https://images.jiabao19.com/images/product/2024-04-01/1711950606074/黄金养肤套.jpg',
      // 'https://images.jiabao19.com/images/product/2024-04-01/1711950606079/眼霜.jpg',
      // {
      //   imgUrl:'https://images.jiabao19.com/images/product/2024-04-01/1711950606076/面膜.jpg'
      // },
      // {
      //   imgUrl:'https://images.jiabao19.com/images/product/2024-04-01/1711950606076/面膜.jpg'
      // }
    ],
    modeIndex: 0, //当前选中模版
    showSelectPop: false,
    showPopTyepTitle: "选择活动",
    activityArr: [
      //   {
      //   value: "1",
      //   label: "西华师大活动"
      // },
      // {
      //   value: "2",
      //   label: "四川大学活动"
      // },
      // {
      //   value: "3",
      //   label: "电子科技大学活动"
      // }
    ],
    uploadData: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getFrontUploadSign();
    this.queryActivityList();
    if (app.globalData.worksPreview && app.globalData.worksPreview.id) {
      this.setData({
        formData: app.globalData.worksPreview,
        modeIndex: app.globalData.worksPreview.modelType,
      })
      if (app.globalData.worksPreview.images.length > 0) {
        this.setData({
          mulImgs: app.globalData.worksPreview.images
        })
      }
      this.queryWorksDetail();
      app.globalData.worksPreview = {}
    }
  },
  queryWorksDetail() {
    wx.showLoading()
    worksDetailReq(this.data.formData.id).then(res => {
      wx.hideLoading()
      if (res.code == 200) {
        this.dealDataBack(res.data);
      }
    }).catch(err => {
      wx.hideLoading()
      wx.showToast({
        title: err || '查询失败',
        icon: "none"
      })
      console.error("JJLog:worksDetailReq", err);
    })
  },
  //处理数据回填
  dealDataBack(resData) {
    let data = this.data.formData;
    this.setData({
      'formData.voteName': data.vote.title,
    })
    if (resData.products && resData.products.length > 0) {
      this.setData({
        productName: resData.products[0].storeName,
        productId: resData.products[0].id,
        'formData.products': resData.products,
      })
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (JSON.stringify(app.globalData.selectProduct) != '{}') {
      console.log("JJLog:选择回调的id是：" + JSON.stringify(app.globalData.selectProduct));
      this.setData({
        productId: app.globalData.selectProduct.id,
        productName: app.globalData.selectProduct.storeName,
        // 'formData.productIds':[app.globalData.selectProduct.id]
      })
    }
    app.globalData.selectProduct = {}
  },
  showSelectPopAction() {
    this.setData({
      showSelectPop: true,
    })
  },
  hidePopup() {
    this.setData({
      showSelectPop: false,
    })
  },
  //清除已选择的商品
  cancelProductNameAction() {
    this.setData({
      productId: '',
      productName: ''
    })
  },
  queryActivityList() {
    queryActivityList(1, 1, 100).then(res => {
      if (res.code == 200) {
        let arr = res.data.list || [];
        let seArr = [];
        //遍历给那个选择活动列表赋值
        if (arr && arr.length > 0) {
          arr.forEach(i => {
            seArr.push({
              value: i.id,
              label: i.title
            })
          })
          this.setData({
            activityArr: seArr,
          })
        }

      }
    }).catch(err => {

    })
  },
  //确认选择
  sureActivitySelect(e) {
    console.log("JJLog:确认选择啦:" + JSON.stringify(e));
    this.setData({
      'formData.voteId': e.detail.result.value,
      'formData.voteName': e.detail.result.label,
      showSelectPop: false
    })
  },
  //删除一张图片
  cancelOneImg(e) {
    let index = e.currentTarget.dataset.index;
    let arr = this.data.mulImgs;
    arr.splice(index, 1);
    this.setData({
      mulImgs: arr
    })
  },
  getFrontUploadSign() {
    getFrontUploadSign().then(res => {
      console.log("JJLog:获取到的图片签名是:" + JSON.stringify(res));
      if (res.code == 200) {
        wx.setStorageSync('ossHost', res.data.host);
        wx.setStorageSync('ossSignature', res.data.signature);
        wx.setStorageSync('ossPolicy', res.data.policy);
        wx.setStorageSync('ossAccessId', res.data.accessId);
        wx.setStorageSync('ossCallBack', res.data.callback);
        wx.setStorageSync('ossDir', res.data.dir);

        this.setData({
          uploadData: res.data
        })
      }
    }).catch(err => {
      console.error("JJLog:getFrontUploadSign", err);
    })
  },

  //上传封面
  pushCoverImgAction() {
    let _this = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        wx.showLoading({
          title: "上传中",
          mask: true,
        });
        // tempFilePath可以作为img标签的src属性显示图片
        console.log('JJLog:选择图片是：' + JSON.stringify(res));
        let imgUrl = res.tempFilePaths[0];
        let expandName = imgUrl.substring(imgUrl.length - 10, imgUrl.length)
        // wx.showLoading({
        //   title: '图片上传中',
        // })
        console.log("JJLog:上传图片签名参数：" + JSON.stringify(_this.data.uploadData));
        wx.uploadFile({
          url: "https://gc-jb.oss-cn-hangzhou.aliyuncs.com",
          filePath: imgUrl,
          name: 'file',
          formData: {
            'key': _this.data.uploadData.dir + "/" + new Date().getTime() + expandName,
            policy: _this.data.uploadData.policy,
            OSSAccessKeyId: _this.data.uploadData.accessId,
            signature: _this.data.uploadData.signature,
            callback: _this.data.uploadData.callback,
          },

          success: function (res) {
            wx.hideLoading()
            console.log("JJLog:图片上传成功===：", res);
            console.log("JJLog:图片上传成功：" + JSON.stringify(res));

            try {
              let resultData = JSON.parse(res.data);
              _this.setData({
                'formData.coverPic': resultData.data.filename,
              })
            } catch (error) {
              wx.showToast({
                title: '图片上传失败，请刷新小程序重试',
                icon: "none",
                duration: 3000,
              })
            }


          },
          fail: function (res) {
            wx.hideLoading()
            wx.showToast({
              title: '上传图片失败',
              icon: "none"
            })
          }
        });

      }
    })
  },
  //拖拽图片更新
  sortImgChange(e) {
    // console.log("JJLog:图片拖拽了：" + JSON.stringify(e));
    // let images = e.detail.images;
    this.setData({
      mulImgs: e.detail.images
    })
  },

  //上传图片方法，多张上传哦。
  pushReplyImgAction() {
    let num = 12;
    let imgLength = this.data.mulImgs.length;
    let arr = this.data.mulImgs || []
    chooseMultipleOSSImgUploadQiniuAction("reply", num - imgLength, this.data.uploadData).then(res => {
      console.log("JJLog:多张图片上传:" + JSON.stringify(res));
      if (res && res.length > 0) {
        res.forEach(i => {
          arr.push(i.imgUrl)
        })
        this.setData({
          mulImgs: arr
        })
      }
    }).catch(err => {
      wx.showToast({
        title: '图片上传失败',
        icon: "none"
      })
    })
  },
  cancelVideo() {
    this.setData({
      'formData.videoUrl': ''
    })
  },
  //删除封面图
  cancelCoverImg() {
    this.setData({
      'formData.coverPic': '',
    })
  },
  //上传视频方法
  pushVideoAction() {
    let _this = this;
    wx.chooseMedia({
      mediaType: ['video'],
      sourceType: ['album', 'camera'],
      // compressed: false,
      // maxDuration: 60,
      camera: 'back',
      success(res) {
        wx.showLoading({
          title: "上传中",
          mask: true,
        });
        console.log("当前传的视频是:" + JSON.stringify(res));

        let imgUrl = res.tempFiles[0].tempFilePath;
        let expandName = imgUrl.substring(imgUrl.length - 10, imgUrl.length)
        // wx.showLoading({
        //   title: '图片上传中',
        // })
        wx.uploadFile({
          url: "https://gc-jb.oss-cn-hangzhou.aliyuncs.com",
          filePath: imgUrl,
          name: 'file',
          formData: {
            'key': _this.data.uploadData.dir + "/" + new Date().getTime() + expandName,
            policy: _this.data.uploadData.policy,
            OSSAccessKeyId: _this.data.uploadData.accessId,
            signature: _this.data.uploadData.signature,
            callback: _this.data.uploadData.callback,
          },

          success: function (res) {
            wx.hideLoading()
            console.log("JJLog:视频上传成功===：", res);
            console.log("JJLog:视频上传成功：" + JSON.stringify(res));

            let resultData = JSON.parse(res.data);
            _this.setData({
              'formData.videoUrl': resultData.data.filename,
            })
          },
          fail: function (res) {
            wx.hideLoading()
            wx.showToast({
              title: '上传视频失败',
              icon: "none"
            })
          }
        });
      },
      fail(err) {
        console.log(err);
      }
    })
  },
  cellInputChange(e) {
    let value = e.detail.value;
    let key = e.currentTarget.dataset.key;
    if (key == 'title') {
      this.setData({
        'formData.title': value,
      })
    }
    if (key == 'createName') {
      this.setData({
        'formData.createName': value,
      })
    }
  },
  bindDescText(e) {
    this.setData({
      'formData.introduce': e.detail.value
    })
  },
  //跳转选择商品
  pushToSelectProduct() {
    wx.navigateTo({
      url: '/featurePackage/pages/selectProduct/selectProduct',
    })
  },
  //模版类型切换
  changeModeTypeAction(e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      'formData.modelType': index,
      modeIndex: index,
    })
  },

  //提交作品
  submitInfoAction() {
    let infoData = this.data.formData;
    if (!infoData.voteId) {
      wx.showToast({
        title: '请选择参加的活动',
        icon: "none"
      })
      return;
    }
    if (!infoData.title.trim()) {
      wx.showToast({
        title: '请填写作品标题',
        icon: "none"
      })
      return;
    }
    if (!infoData.createName.trim()) {
      wx.showToast({
        title: '请填写作品发布人',
        icon: "none"
      })
      return;
    }
    if (!infoData.introduce.trim()) {
      wx.showToast({
        title: '请填写作品简介',
        icon: "none"
      })
      return;
    }
    if (infoData.modelType != 2 && this.data.mulImgs.length < 1) {
      wx.showToast({
        title: '请至少上传一张作品图片',
        icon: "none"
      })
      return;
    }
    if (infoData.modelType == 2 && infoData.videoUlr) {
      wx.showToast({
        title: '请上传视频作品',
        icon: "none"
      })
      return;
    }
    if (infoData.modelType != 2) {
      this.setData({
        'formData.images': this.data.mulImgs
      })
    }
    if (!infoData.coverPic) {
      if (infoData.modelType == 2) {
        this.setData({
          'formData.coverPic': infoData.videoUrl + this.data.videoCoverUrl
        })
      } else {
        this.setData({
          'formData.coverPic': this.data.mulImgs[0]
        })
      }

    }
    if (this.data.productId) {
      this.setData({
        'formData.productIds': [this.data.productId]
      })
    }
    console.log("JJLog:提交数据是:" + JSON.stringify(this.data.formData));

    if (!infoData.id) {
      //创建
      debounce(this.createWorksAction)
    } else {
      //更新
      debounce(this.updateWorksAction)
    }

  },
  //创建
  createWorksAction() {
    wx.showLoading()
    createWorksReq(this.data.formData).then(res => {
      wx.hideLoading()
      if (res.code == 200) {
        wx.showToast({
          title: '创建作品成功',
          icon: "success"
        })
        setTimeout(() => {
          wx.navigateBack();
        }, 3000)
      }
    }).catch(err => {
      wx.hideLoading()
      wx.showToast({
        title: err || '操作失败',
        icon: "none"
      })
      console.error("JJLog:createWorksReq", err)
    })
  },
  //更新
  updateWorksAction() {
    wx.showLoading()
    // 临时写的videoUrl
    // this.setData({
    //   'formData.videoUrl': 'https://images.jiabao19.com/images/product/2024-04-03/1712151156420/绽妍5.mp4',

    //   'formData.coverPic': 'https://images.jiabao19.com/images/product/2024-04-03/1712151156420/绽妍5.mp4' + this.data.videoCoverUrl

    // })
    updateWorksReq(this.data.formData).then(res => {
      wx.hideLoading()
      if (res.code == 200) {
        wx.showToast({
          title: '更新作品成功',
          icon: "success"
        })
        setTimeout(() => {
          wx.navigateBack();
        }, 3000)
      }
    }).catch(err => {
      wx.hideLoading()
      wx.showToast({
        title: err || '操作失败',
        icon: "none"
      })
      console.error("JJLog:updateWorksReq", err)
    })
  },

  //模版预览
  pushToPreviewAction(e) {
    let type = e.currentTarget.dataset.type;
    let title = "";
    let introduce = ``;
    if (type == 2) {
      title = '🔥做项目不管是有创还是无创 术后修护面膜只能选械字号的'
      introduce = `🔥做项目不管是有创还是无创 术后修护面膜只能选械字号的\n✅绽妍蓝敷料入驻各大医院 术后修护专用\n‼️舒缓泛红，修护创面，简直是医用面膜界的标`
    } else {
      title = '摄影艺术 - 化妆品'
      introduce = '光影交错，瞬间永恒：这张摄影作品巧妙地捕捉了自然光与阴影的交织，定格了日常生活中稍纵即逝的美丽瞬间，让人感受到时间静止的魅力。'
    }
    let previewData = {
      id: null,//作品id
      modelType: type, //0:模版1,1：模版2 2：模版3
      title: title, //标题
      createName: "佳宝摄影组", //创建人
      images: [
        'https://images.jiabao19.com/common/tenpone.jpg',
        'https://images.jiabao19.com/common/tenptwo.jpg',
        'https://images.jiabao19.com/common/tenpthree.jpg',
        'https://images.jiabao19.com/common/tenpfour.jpg',

      ], //多图
      introduce: introduce,
      coverPic: "https://images.jiabao19.com/images/product/2024-04-01/1711950606074/黄金养肤套.jpg", //封面
      voteId: "", //活动id
      voteName: "西华师大活动", //活动名称
      videoUrl: "https://images.jiabao19.com/images/product/2024-04-03/1712151156420/绽妍5.mp4", //短视频链接
      // productId: "172",// 商品id
      // productName: "敷尔佳水杨酸杏仁酸焕肤面膜（蛋壳膜）80g/盒",// 商品名称
      voteNum: 0,// 投票数量
      rank: 1,//排名
      viewNum: 120,//浏览量
    }
    app.globalData.worksPreview = previewData;
    if (app.globalData.worksPreview.modelType != 2) {
      wx.navigateTo({
        url: '/featurePackage/pages/works/worksPreview/worksPreview?action=2',
      })
    } else {
      wx.navigateTo({
        url: '/featurePackage/pages/works/worksVideoPreview/worksVideoPreview?action=2',
      })
    }
  },


  //预览作品
  previewWorksAction() {
    // let previewData = {
    //   id: null,//作品id
    //   modelType: this.data.formData.modelType, //0:模版1,1：模版2 2：模版3
    //   title: '佳宝19产品风景', //标题
    //   createName: "9527行动组", //创建人
    //   images: [
    //     'https://images.jiabao19.com/images/product/2024-03-14/1710403654972/%E8%AF%A61.jpg',
    //     'https://images.jiabao19.com/images/product/2024-04-01/1711950606076/面膜.jpg',
    //     'https://images.jiabao19.com/images/product/2024-04-01/1711974874804/%E8%AF%A6%E6%83%85%E5%9B%BE_1.png',
    //     'https://images.jiabao19.com/images/product/2024-04-01/1711950606079/眼霜.jpg',
    //     'https://images.jiabao19.com/images/product/2024-04-01/1711950606076/面膜.jpg',
    //     'https://images.jiabao19.com/images/product/2024-04-01/1711950606074/黄金养肤套.jpg',
    //     'https://images.jiabao19.com/images/product/2024-04-01/1711950606079/眼霜.jpg',
    //     'https://images.jiabao19.com/images/product/2024-04-01/1711950606074/黄金养肤套.jpg',
    //     'https://images.jiabao19.com/images/product/2024-04-01/1711950606074/黄金养肤套.jpg',

    //   ], //多图
    //   introduce: `🔥做项目不管是有创还是无创 术后修护面膜只能选械字号的
    //               ✅绽妍蓝敷料入驻各大医院 术后修护专用`, //简介
    //   coverPic: "https://images.jiabao19.com/images/product/2024-04-01/1711950606074/黄金养肤套.jpg", //封面
    //   voteId: "", //活动id
    //   voteName: "西华师大活动", //活动名称
    //   videoUrl: "", //短视频链接
    //   productId: "172",// 商品id
    //   productName: "敷尔佳水杨酸杏仁酸焕肤面膜（蛋壳膜）80g/盒",// 商品名称
    //   voteNum: 0,// 投票数量
    //   rank: 1,//排名
    //   viewNum: 120,//浏览量
    // }
    let infoData = this.data.formData;
    if (!infoData.voteId) {
      wx.showToast({
        title: '请选择参加的活动',
        icon: "none"
      })
      return;
    }
    if (!infoData.title.trim()) {
      wx.showToast({
        title: '请填写作品标题',
        icon: "none"
      })
      return;
    }
    if (!infoData.createName.trim()) {
      wx.showToast({
        title: '请填写作品发布人',
        icon: "none"
      })
      return;
    }
    if (!infoData.introduce.trim()) {
      wx.showToast({
        title: '请填写作品简介',
        icon: "none"
      })
      return;
    }
    if (infoData.modelType != 2 && this.data.mulImgs.length < 1) {
      wx.showToast({
        title: '请至少上传一张作品图片',
        icon: "none"
      })
      return;
    }
    if (infoData.modelType == 2 && infoData.videoUlr) {
      wx.showToast({
        title: '请上传视频作品',
        icon: "none"
      })
      return;
    }
    if (infoData.modelType != 2) {
      this.setData({
        'formData.images': this.data.mulImgs
      })
    }
    if (!infoData.coverPic) {
      if (infoData.modelType == 2) {
        this.setData({
          'formData.coverPic': infoData.videoUrl + this.data.videoCoverUrl
        })
      } else {
        this.setData({
          'formData.coverPic': this.data.mulImgs[0]
        })
      }

    }
    if (this.data.productId) {
      this.setData({
        'formData.productIds': [this.data.productId]
      })
    }
    app.globalData.worksPreview = this.data.formData;
    if (app.globalData.worksPreview.modelType != 2) {
      wx.navigateTo({
        url: '/featurePackage/pages/works/worksPreview/worksPreview?action=0',
      })
    } else {
      wx.navigateTo({
        url: '/featurePackage/pages/works/worksVideoPreview/worksVideoPreview?action=0',
      })
    }


  },
})